package com.findmeastore.bc.impl;

import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.findmeastore.bc.IProductBc;
import com.findmeastore.bo.CategoryBo;
import com.findmeastore.bo.ProductBo;
import com.findmeastore.dao.ICategoryDAO;
import com.findmeastore.dao.IProductDAO;
import com.findmeastore.dto.ProductDto;

public class ProductBcImpl implements IProductBc{
	private IProductDAO productDao;
	private ICategoryDAO categoryDao;

	public Integer getTotalProductCount(){
		return productDao.getTotalProductCount();
	}
	
	public List<ProductBo> getAllProducts(){
		return productDao.getAllProducts();
	}
	
	public ProductBo getProductById(Integer id){
		return productDao.getProductById(id);
	}
	
	public void saveProduct(ProductDto dto){
		Integer id = dto.getId();
		ProductBo productBo = null;
		if(id!=null&&id>0){//update
			productBo = productDao.getProductById(id);
		}else {//save
			productBo = new ProductBo();
			productBo.setCreationTstamp(new Timestamp(System.currentTimeMillis()));
			productBo.setCreatedByUserId(dto.getModifiedById());
		}
		Map<Integer,CategoryBo> categoryMap = new HashMap<Integer,CategoryBo>();
		for(CategoryBo categoryBo:productBo.getCategories()){
			categoryMap.put(categoryBo.getId(), categoryBo);
		}
		for(Integer categoryId:dto.getCategoryIds()){
			if(categoryMap.containsKey(categoryId)){
				categoryMap.remove(categoryId);
			}else {
				CategoryBo categoryBo = categoryDao.getCategoryById(categoryId);
				productBo.getCategories().add(categoryBo);
			}
		}
		for(CategoryBo categoryBoToRemove:categoryMap.values()){
			productBo.getCategories().remove(categoryBoToRemove);
		}
		productBo.setName(dto.getName());
		productBo.setLastModifiedTstamp(new Timestamp(System.currentTimeMillis()));
		productBo.setLastModifiedByUserId(dto.getModifiedById());

		productDao.saveProduct(productBo);
	}
	
	public IProductDAO getProductDao() {
		return productDao;
	}

	public void setProductDao(IProductDAO productDao) {
		this.productDao = productDao;
	}

	public ICategoryDAO getCategoryDao() {
		return categoryDao;
	}

	public void setCategoryDao(ICategoryDAO categoryDao) {
		this.categoryDao = categoryDao;
	}
}
